package com.xinsoft.jwt;

import com.alibaba.fastjson.JSONObject;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.SysUserDTO;
import com.xinsoft.service.SysUserService;
import com.xinsoft.utils.SysUser;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

/**
 * @author hsm
 * @description 用户鉴权
 * @createDate 2023-04-24
 */
@Slf4j
@RestController
public class JwtAuthController {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private JwtAuthService jwtAuthService;

//    @SysLog(title = "用户登录", businessType = BusinessType.OTHER)
    @PostMapping(value = "/login")
    public Response login(@RequestBody SysUserDTO sysUser) {
            return Response.succeed(jwtAuthService.login(sysUser, Const.Terminal.SYSTEM));
    }

    @GetMapping(value = "/loginByPDA")
    public Response login(@RequestParam(value = "uid", defaultValue = "", required = true) Integer uid ) {
        SysUserDTO sysUser = sysUserService.getSysUser(uid);
        if(sysUser == null){
            return Response.fail("非法用户");
        }
        return Response.succeed(jwtAuthService.login(sysUser, Const.Terminal.PDA));
    }

    @PostMapping(value = "/logout")
    public Response logout(@RequestHeader("${jwt.header}") String token){
        return jwtAuthService.logout(token);
    }

    /**
     * @return cn.o.baseline.common.utils.R
     * @Author Li9527
     * @Description 接收羚羊通知
     * @Date 2021-10-26 09:46:33
     * @Param []
     **/
    @GetMapping("zte/oauth/callback")
    @ApiOperation("接收入回调通知")
    public void callback(HttpServletRequest request) {
        try {
            InputStream is = null;
            is = request.getInputStream();
            StringBuffer stringBuffer = new StringBuffer();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
            reader.close();
            // 获取request消息体
            String data = stringBuffer.toString();
            JSONObject json = JSONObject.parseObject(data);
            log.info("json = {JSONObject} 回调参数: " + json);
            log.info("方案二回调参数,{}",request.getParameter("code"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取用户
     * @param request
     * @return
     */
    @GetMapping("/getUserInfo")
    public Response getUserInfo(HttpServletRequest request){
        SysUserDTO userInfo = jwtAuthService.getUserInfo(request);

        return Response.succeed(userInfo);
    }

}